/*
 * @Descripttion: api
 * @version: 1.0.0
 * @Author: ErCHen
 * @Date: 2022-03-15 19:28:13
 * @LastEditTime: 2022-03-15 20:03:25
 */
import axios from 'axios'
import { BASE_URL, API_PREFIX } from '@/utils/netConf'
import { checkToken, checkUser, getRole } from '@/utils/check'
import router from '@/router'

const config = {
  baseURL: BASE_URL,
  timeout: 1000 * 10,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
}

const WHITE_URL = ['/api/v1/login', '/api/v1/register']

function checkUrl (url: string | undefined): boolean {
  if (url === undefined) {
    return false
  }
  if (url === '/api/v1/login') {
    return true
  }
  if (url.startsWith('/api/v1/register')) {
    return true
  }
  if (url.startsWith('/api/v1/user/reset')) {
    return true
  }
  return false
}

const instance = axios.create(config)
instance.interceptors.request.use(
  (config) => {
    if (config.headers !== undefined) {
      let tup = ''
      if (checkUser()) {
        tup = '_g'
      }
      const url = config.url
      const token = checkToken()
      if (!checkUrl(url) && token.length === 0) {
        // alert('登录过期,请重新登录')
        setTimeout(() => {
          router.replace({
            path: '/login'
          })
        }, 500)
        return Promise.reject(new Error('Login Invalid'))
      } else {
        config.headers.Authorization = token + tup + '&' + getRole()
      }
    }
    return config
  },
  error => {
    // console.log('请求错误')
    return Promise.reject(error)
  }
)

instance.interceptors.response.use((response) => {
  if (response.status === 200) {
    const resp = response.data
    if (resp.code === 101) {
      // alert('登录过期,请重新登录')
      setTimeout(() => {
        router.replace({
          path: '/login'
        })
      }, 500)
      return
    }
    return response
  }
}, (error) => {
  return Promise.reject(error)
})

export default {
  get: function (url: string) {
    return instance.get(API_PREFIX + url)
  },
  post: function (url: string, data: any) {
    return instance.post(API_PREFIX + url, data)
  }
}
